<template>
  <div class="app-container">
    <el-card>
      <el-row :gutter="10" v-if="nodeInfo.length > 0">
        <el-col :xs="0" :sm="4" :md="4" :lg="4" :xl="2">
          <div>
            <el-tag>节点数: {{ nodeCount }}</el-tag>
          </div>
          <div class="one-img"><img class="productImg"
                                    src="@/assets/images/shebei.png"></div>
        </el-col>
        <el-col :xs="24" :sm="20" :md="20" :lg="20" :xl="22">
          <el-descriptions title="节点信息">
            <el-descriptions-item label="节点名称:">{{ nodeInfo[0].node }}</el-descriptions-item>
            <el-descriptions-item label="运行时长:">{{ formatDuration(nodeInfo[0].uptime) }}</el-descriptions-item>
            <el-descriptions-item label="连接数:">{{ nodeInfo[0].connections }}</el-descriptions-item>
            <el-descriptions-item label="订阅数:">{{ monitorCurrents.subscriptions }}</el-descriptions-item>
            <el-descriptions-item label="主题数:">{{ monitorCurrents.topics }}</el-descriptions-item>
            <el-descriptions-item label="节点角色:">{{ nodeInfo[0].role }}</el-descriptions-item>
            <el-descriptions-item label="版本信息:">
              <el-text type="success">{{ nodeInfo[0].version }}({{ nodeInfo[0].edition }})</el-text>
            </el-descriptions-item>
            <el-descriptions-item label="节点状态:">
              <el-text v-if="nodeInfo[0].node_status === 'running'" type="success">正常</el-text>
              <el-text v-else type="danger">离线</el-text>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <el-empty description="暂无节点信息" style="height: 180px;" v-else/>
    </el-card>
    <el-card class="card-content">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="RefreshRight" @click="Refresh" v-hasPermi="['iot:mqtt:list']">刷新</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="Clients">
        <el-table-column label="客户端ID" align="center" prop="clientid" width="200"/>
        <el-table-column label="节点名称" align="center" prop="node"/>
        <el-table-column label="连接状态" align="center" prop="connected">
          <template #default="scope">
            <el-tag v-if="scope.row.connected === true" type="success">在线</el-tag>
            <el-tag v-else type="danger">离线</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="IP" align="center" prop="ip_address"/>
        <el-table-column label="端口" align="center" prop="port"/>
        <el-table-column label="保持活动间隔" align="center" prop="keepalive"/>
        <el-table-column label="连接时间" align="center" prop="created_at" width="200">
          <template #default="scope">
            <el-text>{{ formatISODate(scope.row.created_at) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="最后一次连接时间" align="center" prop="connected_at" width="200">
          <template #default="scope">
            <el-text>{{ formatISODate(scope.row.connected_at) }}</el-text>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="danger" icon="Close" @click="offline(scope.row)"
                       v-hasPermi="['iot:mqtt:clients']">下线
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          v-show="total>0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getClientsList"
      />
    </el-card>
  </div>
</template>

<script setup name="Mqtt">
import {listClients, listNode, listMonitorCurrent, clients} from "@/api/iot/mqtt";
import {onMounted} from "vue";

const {proxy} = getCurrentInstance();

const total = ref(0);
const nodeCount = ref(0);
const nodeInfo = ref([]);
const monitorCurrents = ref({});
const Clients = ref([]);
const loading = ref(true);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
})

/**
 * 客户端下线
 * @param row
 * @returns {Promise<void>}
 */
const offline = async (row) => {
  const res = await clients(row.clientid);
  loading.value = true;
  getClientsList();
}

/**
 * 刷新方法
 * @constructor
 */
const Refresh = () => {
  loading.value = true;
  getClientsList();
}

/**
 * 计算运行时长
 * @param seconds
 * @returns {string}
 */
const formatDuration = (seconds) => {
  seconds = Math.floor(seconds / 1000);
  const timeUnits = [
    {unit: '天', seconds: 86400},
    {unit: '小时', seconds: 3600},
    {unit: '分', seconds: 60},
    {unit: '秒', seconds: 1}
  ];
  const result = [];
  for (const {unit, seconds: unitSeconds} of timeUnits) {
    const value = Math.floor(seconds / unitSeconds);
    if (value > 0) {
      result.push(`${value}${unit}`);
      seconds %= unitSeconds;
    }
  }
  return result.join(' ');
}

const formatISODate = (isoDate) => {
  var date = new Date(isoDate);
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var seconds = date.getSeconds();
  function pad(number) {
    return number < 10 ? '0' + number : number;
  }
  return `${year}年${pad(month)}月${pad(day)}日${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
}
const getClientsList = async () => {
  const ans = await listClients(queryParams.value);
  Clients.value = ans.rows;
  total.value = ans.total;
  loading.value = false;
}

onMounted(async () => {
  const res = await listNode();
  if (res.data && res.data.length > 0) {
    nodeCount.value = res.data.length;
    nodeInfo.value = res.data;
    const res2 = await listMonitorCurrent();
    monitorCurrents.value = res2.data;
  }
  await getClientsList();
})

</script>

<style scoped>
.one-img {
  width: 100%;
  margin-top: 20px;
}

.productImg {
  width: 100px;
}
.card-content{
  margin-top: 10px;
}
</style>